import java.util.*;

/**
* @description: 周赛308 t4
* @author hewei
* @date 2022/8/28 11:28
* @version 1.0
*/

public class BuildMatrix {

    public static void main(String[] args) {
        BuildMatrix buildMatrix = new BuildMatrix();
        int[][] nums = {{1,2},{3,2}};
        System.out.println(Arrays.toString(buildMatrix.topoSort(nums, 3)));
    }

    public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {
        int[] row = topoSort(rowConditions, k);
        int[] col = topoSort(colConditions, k);
        if (row.length == 0 || col.length == 0) return new int[][]{};
        int[][] ans = new int[k][k];
        for (int i = 0; i < k; i++) {
            int x = row[i];
            int y = col[i];
            ans[x][y] = i + 1;
        }
        return ans;
    }

    public int[] topoSort(int[][] edge, int k) {
        int[] res = new int[k];
        Arrays.fill(res, -1);
        List<Integer>[] list = new ArrayList[k];
        int[] indeg = new int[k];
        for (int[] e : edge) {
            int a = e[0] - 1;
            int b = e[1] - 1;
            if (list[a] == null) list[a] = new ArrayList<>();
            list[a].add(b);
            indeg[b]++;
        }
        int index = 0;
        Deque<Integer> queue = new LinkedList<>();
        for (int i = 0; i < k; i++) {
            if (indeg[i] == 0) queue.add(i);
        }
        while (!queue.isEmpty()) {
            Integer poll = queue.poll();
            res[poll] = index++;
            if (list[poll] != null) {
                for (Integer a : list[poll]) {
                    indeg[a]--;
                    if (indeg[a] == 0) queue.add(a);
                }
            }
        }
        if (k != index) return new int[0];
        return res;
    }
}
